#include <sys/types.h>
#include <sys/ipc.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

char SEM_NAME[] = "process1";
char SEM_NAME2[] = "process2";

int main(int argc, char **argv) {
    sem_t *mutex, *mutex2;
    int fd;

    // 初始化信号量，mutex 初始 0，mutex2 初始 1
    mutex = sem_open(SEM_NAME, O_CREAT, 0666, 0);
    mutex2 = sem_open(SEM_NAME2, O_CREAT, 0666, 1);
    if (mutex == SEM_FAILED || mutex2 == SEM_FAILED) {
        perror("unable to execute semaphore");
        sem_close(mutex);
        sem_close(mutex2);
        exit(-1);
    }

    // 以写模式打开文件，保持描述符不关闭
    fd = open("a.txt", O_CREAT | O_WRONLY | O_APPEND, 0666);
    if (fd == -1) {
        perror("open failed");
        sem_close(mutex);
        sem_close(mutex2);
        exit(-1);
    }

    while (1) {
        sem_wait(mutex2);      // 等待信号量，P 操作
        write(fd, "DEF\n", 4); // 写入 "DEF\n"
        sem_post(mutex);       // 释放信号量，V 操作
        sleep(1);
    }

    sem_close(mutex);
    sem_close(mutex2);
    sem_unlink(SEM_NAME);
    sem_unlink(SEM_NAME2);
    close(fd);
    return 0;
}
